const jwt=require('jsonwebtoken')

//认证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1] // Bearer TOKEN

  if (!token) {
    return res.json({
      code: '2006',
      msg: '访问被拒绝，未提供token',
      data: null
    })
  }

  try {
    const verified = jwt.verify(token, 'my_secret')
    req.user = verified
    next()
  } catch (err) {
    return res.json({
      code: '2007',
      msg: '无效的token',
      data: null
    })
  }
}

module.exports = authenticateToken;